import mongoose, { Document, Schema } from 'mongoose';

export interface ICoupon extends Document {
  code: string;
  name: string;
  description: string;
  type: 'percentage' | 'fixed' | 'shipping';
  value: number;
  minPurchase: number;
  maxDiscount: number;
  startDate: Date;
  endDate: Date;
  isActive: boolean;
  usageLimit: number;
  usageCount: number;
  categories: mongoose.Types.ObjectId[];
  products: mongoose.Types.ObjectId[];
  excludedProducts: mongoose.Types.ObjectId[];
  userRestriction: 'all' | 'new' | 'vip';
  createdAt: Date;
  updatedAt: Date;
}

const CouponSchema: Schema = new Schema(
  {
    code: {
      type: String,
      required: true,
      unique: true,
      uppercase: true,
      trim: true,
    },
    name: {
      type: String,
      required: true,
      trim: true,
    },
    description: {
      type: String,
      default: '',
    },
    type: {
      type: String,
      enum: ['percentage', 'fixed', 'shipping'],
      required: true,
    },
    value: {
      type: Number,
      required: true,
      min: 0,
    },
    minPurchase: {
      type: Number,
      default: 0,
      min: 0,
    },
    maxDiscount: {
      type: Number,
      default: 0,
      min: 0,
    },
    startDate: {
      type: Date,
      default: Date.now,
    },
    endDate: {
      type: Date,
      required: true,
    },
    isActive: {
      type: Boolean,
      default: true,
    },
    usageLimit: {
      type: Number,
      default: 0, // 0表示无限制
    },
    usageCount: {
      type: Number,
      default: 0,
    },
    categories: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Category',
      },
    ],
    products: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Product',
      },
    ],
    excludedProducts: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Product',
      },
    ],
    userRestriction: {
      type: String,
      enum: ['all', 'new', 'vip'],
      default: 'all',
    },
  },
  {
    timestamps: true,
  }
);

// 创建索引
CouponSchema.index({ code: 1 });
CouponSchema.index({ startDate: 1, endDate: 1 });
CouponSchema.index({ isActive: 1 });

export default mongoose.model<ICoupon>('Coupon', CouponSchema); 